<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分类管理 - 记账助手</title>
    <link rel="stylesheet" href="styles.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/Sortable.min.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            position: relative;
        }
        
        .page-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin: 0;
            text-align: center;
        }
        
        .back-btn {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 0.9rem;
            cursor: pointer;
        }
        
        .back-btn:hover {
            background: rgba(255,255,255,0.3);
        }
        
        .category-tabs {
            display: flex;
            background: white;
            border-radius: 0;
            margin-bottom: 20px;
            overflow: hidden;
            box-shadow: none;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .category-tab {
            flex: 1;
            padding: 12px;
            background: white;
            border: none;
            font-size: 1rem;
            font-weight: 500;
            color: #666;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .category-tab.active {
            background: #667eea;
            color: white;
        }
        
        .category-content {
            background: white;
            border-radius: 0;
            padding: 20px;
            box-shadow: none;
        }
        
        .category-list-container {
            background: white;
            border-radius: 0;
            overflow: hidden;
            margin-top: 10px;
        }
        
        .category-section {
            display: none;
        }
        
        .category-section.active {
            display: block;
        }
        
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
        }
        
        .section-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: #333;
        }
        
        .add-category-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 0.9rem;
            cursor: pointer;
            transition: background 0.2s;
        }
        
        .add-category-btn:hover {
            background: #218838;
        }
        
        .list-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .list-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #333;
            margin: 0;
        }
        
        .add-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 0.85rem;
            cursor: pointer;
            transition: background 0.2s;
        }
        
        .add-btn:hover {
            background: #218838;
        }
        
        .category-list {
            list-style: none;
            padding: 0;
            margin: 0;
            background: none;
        }
        
        .category-item {
            padding: 12px 15px !important;
            margin-bottom: 0 !important;
            min-height: auto !important;
            display: flex !important;
            align-items: center !important;
            background: none !important;
            border: none !important;
            box-shadow: none !important;
            border-radius: 0 !important;
            border-bottom: 1px solid #f0f0f0 !important;
            transition: background-color 0.2s;
            cursor: move;
        }
        
        .category-item:hover {
            background-color: #f8f9fa;
        }
        
        .category-item:last-child {
            border-bottom: none;
        }
        
        .category-info {
            margin-left: 8px !important;
            flex: 1 !important;
            display: flex !important;
            align-items: center !important;
        }
        
        .drag-handle {
            color: #999;
            cursor: move;
            font-size: 16px !important;
            margin-right: 12px;
            flex-shrink: 0 !important;
            width: 20px;
            text-align: center;
        }
        
        .category-icon {
            width: 32px !important;
            height: 32px !important;
            border-radius: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px !important;
            background: transparent;
            border: none;
            flex-shrink: 0 !important;
        }
        
        .category-name {
            font-size: 14px !important;
            font-weight: 500;
            color: #333;
            margin: 0 !important;
            flex: 1 !important;
            cursor: pointer;
            padding: 6px 8px;
            border-radius: 4px;
            transition: background-color 0.2s;
            line-height: 1.3 !important;
        }
        
        .category-name:hover {
            background-color: #f0f0f0;
        }
        
        .category-actions {
            display: flex !important;
            gap: 4px;
        }
        
        .action-btn {
            width: 28px !important;
            height: 28px !important;
            border-radius: 0 !important;
            border: none !important;
            cursor: pointer !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            font-size: 12px !important;
            transition: all 0.2s ease;
            flex-shrink: 0 !important;
            margin-left: 4px;
        }
        
        .edit-btn {
            background: #f8f9fa;
            color: #666;
        }
        
        .edit-btn:hover {
            background: #e9ecef;
            color: #333;
        }
        
        .delete-btn {
            background: #f8f9fa;
            color: #666;
        }
        
        .delete-btn:hover {
            background: #e9ecef;
            color: #dc3545;
        }
        
        .subcategory-btn {
            background: #f8f9fa;
            color: #666;
        }
        
        .subcategory-btn:hover {
            background: #e9ecef;
            color: #667eea;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .breadcrumb {
            background: none;
            padding: 0;
            margin-bottom: 15px;
        }
        
        .breadcrumb-item {
            font-size: 14px;
            color: #666;
        }
        
        .breadcrumb-item.active {
            color: #333;
            font-weight: 500;
        }
        
        .breadcrumb-item + .breadcrumb-item::before {
            content: ">";
            color: #999;
        }
        
        .icon-option {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            background: white;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 2px solid transparent;
        }
        
        .icon-option:hover {
            background: #e2e8f0;
            transform: scale(1.1);
        }
        
        .icon-option.selected {
            background: #667eea;
            color: white;
            border-color: #5a6fd8;
            transform: scale(1.1);
        }
        
        .sortable-ghost {
            opacity: 0.4;
        }
        
        .toast-message {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #28a745;
            color: white;
            padding: 12px 20px;
            border-radius: 6px;
            z-index: 9999;
            box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        }
        
        .subcategory-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 10px;
        }
        
        .subcategory-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 12px 8px;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
            border: 2px solid transparent;
            position: relative;
        }
        
        .subcategory-item:hover {
            background: #e2e8f0;
            border-color: #cbd5e0;
        }
        
        .subcategory-icon {
            font-size: 16px;
            margin-bottom: 5px;
        }
        
        .subcategory-name {
            font-size: 12px;
            color: #4a5568;
            font-weight: 500;
        }
        
        .subcategory-delete {
            position: absolute;
            top: -5px;
            right: -5px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #fed7d7;
            color: #e53e3e;
            border: none;
            font-size: 10px;
            cursor: pointer;
            display: none;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .subcategory-item:hover .subcategory-delete {
            display: flex;
        }
        
        .subcategory-delete:hover {
            background: #e53e3e;
            color: white;
        }
        
        .add-subcategory {
            background: linear-gradient(135deg, #e6f3ff, #bee3f8);
            border: 2px dashed #3182ce;
            color: #3182ce;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .add-subcategory:hover {
            background: linear-gradient(135deg, #3182ce, #2c5aa0);
            color: white;
            border-color: #2c5aa0;
        }
        
        .modal-content {
            border-radius: 20px;
            border: none;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }
        
        .modal-header {
            border-bottom: 2px solid #e2e8f0;
            border-radius: 20px 20px 0 0;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }
        
        .modal-title {
            font-weight: 700;
        }
        
        .btn-close {
            filter: brightness(0) invert(1);
        }
        
        .form-control {
            border-radius: 12px;
            border: 2px solid #e2e8f0;
            padding: 12px 15px;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .icon-selector {
            display: grid;
            grid-template-columns: repeat(8, 1fr);
            gap: 10px;
            max-height: 200px;
            overflow-y: auto;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 12px;
            border: 2px solid #e2e8f0;
        }
        
        .icon-item {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            background: white;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 2px solid transparent;
        }
        
        .icon-item:hover {
            background: #e2e8f0;
            transform: scale(1.1);
        }
        
        .icon-item.selected {
            background: #667eea;
            color: white;
            border-color: #5a6fd8;
            transform: scale(1.1);
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            border: none;
            border-radius: 12px;
            padding: 12px 25px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, #5a6fd8, #6b46a3);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-secondary {
            background: #6c757d;
            border: none;
            border-radius: 12px;
            padding: 12px 25px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #64748b;
        }
        
        .empty-icon {
            font-size: 64px;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        
        .empty-text {
            font-size: 18px;
            margin-bottom: 10px;
        }
        
        .empty-subtext {
            font-size: 14px;
            opacity: 0.7;
        }
        
        /* 移动端优化 */
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .page-header {
                padding: 15px;
                margin-bottom: 15px;
            }
            
            .page-title {
                font-size: 1.3rem;
            }
            
            .back-btn {
                left: 15px;
                padding: 6px 10px;
                font-size: 0.8rem;
            }
            
            .category-content {
                padding: 15px;
            }
            
            .list-header {
                margin-bottom: 12px;
            }
            
            .list-title {
                font-size: 1rem;
            }
            
            .add-btn {
                padding: 6px 10px;
                font-size: 0.8rem;
            }
            
            .category-item {
                padding: 8px 12px;
            }
            
            .category-icon {
                width: 26px;
                height: 26px;
                font-size: 13px;
            }
            
            .category-name {
                font-size: 13px;
            }
            
            .action-btn {
                width: 22px;
                height: 22px;
                font-size: 10px;
            }
            
            .drag-handle {
                font-size: 13px;
                margin-right: 6px;
            }
        }
        
        /* 小屏手机优化 */
        @media (max-width: 480px) {
            .container {
                padding: 8px;
            }
            
            .page-header {
                padding: 12px;
                margin-bottom: 12px;
            }
            
            .page-title {
                font-size: 1.1rem;
            }
            
            .back-btn {
                left: 12px;
                padding: 5px 8px;
                font-size: 0.75rem;
            }
            
            .category-content {
                padding: 12px;
            }
            
            .list-header {
                margin-bottom: 10px;
            }
            
            .list-title {
                font-size: 0.9rem;
            }
            
            .add-btn {
                padding: 5px 8px;
                font-size: 0.75rem;
            }
            
            .category-item {
                padding: 6px 10px;
            }
            
            .category-icon {
                width: 24px;
                height: 24px;
                font-size: 12px;
            }
            
            .category-name {
                font-size: 12px;
            }
            
            .action-btn {
                width: 20px;
                height: 20px;
                font-size: 9px;
            }
            
            .drag-handle {
                font-size: 12px;
                margin-right: 4px;
            }
            
            .category-info {
                gap: 6px;
            }
            
            .category-actions {
                gap: 3px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="page-header">
            <button class="back-btn" onclick="goBack()">← 返回</button>
            <h1 class="page-title">分类管理</h1>
        </div>
        
        <div class="category-tabs">
            <button class="category-tab active" data-type="expense">支出分类</button>
            <button class="category-tab" data-type="income">收入分类</button>
        </div>
        
        <div class="category-content">
            <!-- 支出分类内容 -->
            <div id="expense-content" class="tab-content active">
                <div class="list-header">
                    <h3 class="list-title">一级分类</h3>
                    <button class="add-btn" onclick="showAddCategoryModal('expense', 1)">+ 添加</button>
                </div>
                <div class="category-list-container">
                    <ul class="category-list" id="expense-list">
                        <!-- 一级分类列表将在这里动态生成 -->
                    </ul>
                </div>
            </div>
            
            <!-- 收入分类内容 -->
            <div id="income-content" class="tab-content">
                <div class="list-header">
                    <h3 class="list-title">一级分类</h3>
                    <button class="add-btn" onclick="showAddCategoryModal('income', 1)">+ 添加</button>
                </div>
                <div class="category-list-container">
                    <ul class="category-list" id="income-list">
                        <!-- 一级分类列表将在这里动态生成 -->
                    </ul>
                </div>
            </div>
            
            <!-- 二级分类内容 -->
            <div id="subcategory-content" class="tab-content" style="display: none;">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb" id="breadcrumb">
                        <!-- 面包屑导航将在这里动态生成 -->
                    </ol>
                </nav>
                <div class="list-header">
                    <h3 class="list-title" id="subcategory-title">二级分类</h3>
                    <button class="add-btn" onclick="showAddSubcategoryModal()">+ 添加</button>
                </div>
                <div class="category-list-container">
                    <ul class="category-list" id="subcategory-list">
                        <!-- 二级分类列表将在这里动态生成 -->
                    </ul>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 添加分类模态框 -->
    <div class="modal fade" id="addCategoryModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加分类</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addCategoryForm">
                        <div class="mb-3">
                            <label class="form-label">分类名称</label>
                            <input type="text" class="form-control" id="categoryName" placeholder="请输入分类名称" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">选择图标</label>
                            <div class="icon-selector" id="iconSelector">
                                <!-- 动态生成图标 -->
                            </div>
                        </div>
                        <input type="hidden" id="categoryType">
                        <input type="hidden" id="selectedIcon">
                        <input type="hidden" id="editingCategoryId">
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveCategoryBtn">保存</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 添加二级分类模态框 -->
    <div class="modal fade" id="addSubcategoryModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加二级分类</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addSubcategoryForm">
                        <div class="mb-3">
                            <label class="form-label">二级分类名称</label>
                            <input type="text" class="form-control" id="subcategoryName" placeholder="请输入二级分类名称" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">选择图标</label>
                            <div class="icon-selector" id="subcategoryIconSelector">
                                <!-- 动态生成图标 -->
                            </div>
                        </div>
                        <input type="hidden" id="parentCategoryId">
                        <input type="hidden" id="selectedSubcategoryIcon">
                        <input type="hidden" id="editingSubcategoryId">
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveSubcategoryBtn">保存</button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 分类数据
        let categoryData = {
            expense: [
                { id: 1, name: '餐饮', icon: '🍽️', subcategories: [
                    { id: 1, name: '三餐', icon: '🍚' },
                    { id: 2, name: '宵夜', icon: '🌙' },
                    { id: 3, name: '零食', icon: '🍿' },
                    { id: 4, name: '饮料', icon: '🥤' }
                ]},
                { id: 2, name: '交通', icon: '🚗', subcategories: [
                    { id: 1, name: '公交', icon: '🚌' },
                    { id: 2, name: '地铁', icon: '🚇' },
                    { id: 3, name: '打车', icon: '🚕' },
                    { id: 4, name: '加油', icon: '⛽' }
                ]},
                { id: 3, name: '购物', icon: '🛍️', subcategories: [
                    { id: 1, name: '服装', icon: '👕' },
                    { id: 2, name: '数码', icon: '💻' },
                    { id: 3, name: '日用品', icon: '🧴' }
                ]},
                { id: 4, name: '娱乐', icon: '🎮', subcategories: [
                    { id: 1, name: '电影', icon: '🎬' },
                    { id: 2, name: '游戏', icon: '🎯' },
                    { id: 3, name: 'KTV', icon: '🎵' }
                ]}
            ],
            income: [
                { id: 1, name: '工资', icon: '💰', subcategories: [
                    { id: 1, name: '基本工资', icon: '💵' },
                    { id: 2, name: '奖金', icon: '🏆' },
                    { id: 3, name: '津贴', icon: '💳' }
                ]},
                { id: 2, name: '兼职', icon: '💼', subcategories: [
                    { id: 1, name: '外卖', icon: '🛵' },
                    { id: 2, name: '代驾', icon: '🚗' },
                    { id: 3, name: '家教', icon: '📚' }
                ]},
                { id: 3, name: '理财', icon: '📈', subcategories: [
                    { id: 1, name: '股票', icon: '📊' },
                    { id: 2, name: '基金', icon: '💹' },
                    { id: 3, name: '利息', icon: '🏦' }
                ]}
            ]
        };
        
        // 可选图标
        const availableIcons = [
            '🍽️', '🚗', '🛍️', '🎮', '🏥', '📚', '💰', '💼', '📈', '🎁',
            '🏠', '📱', '✈️', '🎵', '⚽', '🎨', '🔧', '💊', '🍕', '☕',
            '🚌', '🚇', '🚕', '⛽', '🅿️', '👕', '💻', '🧴', '💄', '🎬',
            '🎯', '🏃', '🏊', '🎸', '📖', '✏️', '💳', '🏦', '📊', '🎂'
        ];
        
        let currentCategoryType = 'expense';
        let currentParentCategory = null;
        let selectedIcon = '🍽️';
        let sortableInstances = [];
        
        // 页面加载完成后初始化
        $(document).ready(function() {
            initializePage();
        });
        
        function initializePage() {
            renderCategoryList('expense');
            setupEventListeners();
            setupSortable();
        }
        
        function setupEventListeners() {
            // 分类标签切换
            $('.category-tab').click(function() {
                const type = $(this).data('type');
                switchCategoryType(type);
            });
        }
        
        function switchCategoryType(type) {
            currentCategoryType = type;
            
            // 更新标签状态
            $('.category-tab').removeClass('active');
            $(`.category-tab[data-type="${type}"]`).addClass('active');
            
            // 显示对应内容
            $('.tab-content').hide();
            $(`#${type}-content`).show();
            
            // 重置面包屑
            updateBreadcrumb([{ name: '分类管理', action: null }]);
            
            // 渲染分类列表
            renderCategoryList(type);
        }
        
        function renderCategoryList(type) {
            const container = $(`#${type}-list`);
            container.empty();
            
            const categories = categoryData[type];
            
            if (categories.length === 0) {
                container.append(`
                    <li class="empty-state">
                        <div class="empty-icon">📝</div>
                        <div class="empty-text">暂无${type === 'expense' ? '支出' : '收入'}分类</div>
                        <div class="empty-subtext">点击上方"添加"按钮创建新分类</div>
                    </li>
                `);
                return;
            }
            
            categories.forEach(category => {
                const listItem = createCategoryListItem(category, type, false);
                container.append(listItem);
            });
            
            setupSortable();
        }
        
        function renderSubcategoryList(parentCategory) {
            const container = $('#subcategory-list');
            container.empty();
            
            const subcategories = parentCategory.subcategories || [];
            
            subcategories.forEach(subcategory => {
                const listItem = createCategoryListItem(subcategory, currentCategoryType, true);
                container.append(listItem);
            });
            
            setupSortable();
        }
        
        function createCategoryListItem(category, type, isSubcategory) {
            const subcategoryBtn = !isSubcategory ? 
                `<button class="action-btn subcategory-btn" onclick="showSubcategories('${category.id}')" title="二级管理">⚙</button>` : '';
            
            return `
                <li class="category-item" data-id="${category.id}">
                    <span class="drag-handle">⋮⋮</span>
                    <div class="category-icon">${category.icon}</div>
                    <div class="category-info">
                        <span class="category-name">${category.name}</span>
                    </div>
                    <div class="category-actions">
                        ${subcategoryBtn}
                        <button class="action-btn edit-btn" onclick="editCategory('${category.id}', ${isSubcategory})" title="编辑">✏</button>
                        <button class="action-btn delete-btn" onclick="deleteCategory('${category.id}', ${isSubcategory})" title="删除">🗑</button>
                    </div>
                </li>
            `;
        }
        
        function setupSortable() {
            // 清除之前的sortable实例
            sortableInstances.forEach(instance => {
                if (instance && instance.destroy) {
                    instance.destroy();
                }
            });
            sortableInstances = [];
            
            // 为每个分类列表设置拖拽排序
            document.querySelectorAll('.category-list').forEach(list => {
                const sortable = new Sortable(list, {
                    animation: 150,
                    ghostClass: 'sortable-ghost',
                    handle: '.drag-handle',
                    onEnd: function(evt) {
                        const listType = evt.to.id.includes('expense') ? 'expense' : 
                                       evt.to.id.includes('income') ? 'income' : 'subcategory';
                        
                        if (listType === 'subcategory') {
                            updateSubcategoryOrder(evt.oldIndex, evt.newIndex);
                        } else {
                            updateCategoryOrder(listType, evt.oldIndex, evt.newIndex);
                        }
                        
                        showToast('排序已更新');
                    }
                });
                sortableInstances.push(sortable);
            });
        }
        
        function updateCategoryOrder(type, oldIndex, newIndex) {
            // 更新分类顺序
            const categories = categoryData[type];
            const movedItem = categories.splice(oldIndex, 1)[0];
            categories.splice(newIndex, 0, movedItem);
            
            // 保存到本地存储
            localStorage.setItem('categoryData', JSON.stringify(categoryData));
        }
        
        function updateSubcategoryOrder(oldIndex, newIndex) {
            // 更新二级分类顺序
            if (currentParentCategory && currentParentCategory.subcategories) {
                const subcategories = currentParentCategory.subcategories;
                const movedItem = subcategories.splice(oldIndex, 1)[0];
                subcategories.splice(newIndex, 0, movedItem);
                
                // 保存到本地存储
                localStorage.setItem('categoryData', JSON.stringify(categoryData));
            }
        }
        
        function showSubcategories(categoryId) {
            const category = findCategoryById(categoryId, currentCategoryType);
            if (!category) return;
            
            currentParentCategory = category;
            
            // 隐藏主分类列表，显示二级分类列表
            $('.tab-content').hide();
            $('#subcategory-content').show();
            
            // 更新标题和面包屑
            $('#subcategory-title').text(`${category.name} - 二级分类`);
            updateBreadcrumb([
                { name: '分类管理', action: () => goBackToMain() },
                { name: category.name, action: null }
            ]);
            
            // 渲染二级分类列表
            renderSubcategoryList(category);
        }
        
        function goBackToMain() {
            currentParentCategory = null;
            $('.tab-content').hide();
            $(`#${currentCategoryType}-content`).show();
            updateBreadcrumb([{ name: '分类管理', action: null }]);
        }
        
        function goBack() {
            if (currentParentCategory) {
                goBackToMain();
            } else {
                history.back();
            }
        }
        
        function updateBreadcrumb(items) {
            const breadcrumb = $('#breadcrumb');
            breadcrumb.empty();
            
            items.forEach((item, index) => {
                const isLast = index === items.length - 1;
                const li = $(`<li class="breadcrumb-item ${isLast ? 'active' : ''}"></li>`);
                
                if (isLast || !item.action) {
                    li.text(item.name);
                } else {
                    const link = $(`<a href="#">${item.name}</a>`);
                    link.click(e => {
                        e.preventDefault();
                        item.action();
                    });
                    li.append(link);
                }
                
                breadcrumb.append(li);
            });
        }
        
        function findCategoryById(id, type) {
            return categoryData[type].find(cat => cat.id === id);
        }
        
        function findSubcategoryById(id, parentCategory) {
            return parentCategory.subcategories.find(sub => sub.id === id);
        }
        
        function showAddCategoryModal(type, level) {
            currentCategoryType = type;
            selectedIcon = availableIcons[0];
            
            const modalTitle = '添加分类';
            const modal = createCategoryModal(modalTitle, '', selectedIcon, 'add');
            
            $('body').append(modal);
            $('#categoryModal').modal('show');
        }
        
        function showAddSubcategoryModal() {
            selectedIcon = availableIcons[0];
            
            const modal = createCategoryModal('添加二级分类', '', selectedIcon, 'addSub');
            
            $('body').append(modal);
            $('#categoryModal').modal('show');
        }
        
        function editCategory(categoryId, isSubcategory) {
            let category;
            
            if (isSubcategory) {
                category = findSubcategoryById(categoryId, currentParentCategory);
            } else {
                category = findCategoryById(categoryId, currentCategoryType);
            }
            
            if (!category) return;
            
            selectedIcon = category.icon;
            const action = isSubcategory ? 'editSub' : 'edit';
            
            const modal = createCategoryModal('编辑分类', category.name, selectedIcon, action, categoryId);
            
            $('body').append(modal);
            $('#categoryModal').modal('show');
        }
        
        function createCategoryModal(title, name, icon, action, categoryId = null) {
            const iconOptionsHtml = availableIcons.map(iconOption => 
                `<div class="icon-option ${iconOption === icon ? 'selected' : ''}" data-icon="${iconOption}">${iconOption}</div>`
            ).join('');
            
            return `
                <div class="modal fade" id="categoryModal" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">${title}</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <div class="mb-3">
                                    <label class="form-label">分类名称</label>
                                    <input type="text" class="form-control" id="categoryNameInput" value="${name}" placeholder="请输入分类名称">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">选择图标</label>
                                    <div class="icon-selector">
                                        ${iconOptionsHtml}
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary" onclick="handleCategoryAction('${action}', ${categoryId})">
                                    ${action.includes('add') ? '添加' : '保存'}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }
        
        function handleCategoryAction(action, categoryId) {
            const name = $('#categoryNameInput').val().trim();
            
            if (!name) {
                alert('请输入分类名称');
                return;
            }
            
            switch (action) {
                case 'add':
                    addCategory(name);
                    break;
                case 'addSub':
                    addSubcategory(name);
                    break;
                case 'edit':
                    updateCategory(categoryId, name);
                    break;
                case 'editSub':
                    updateSubcategory(categoryId, name);
                    break;
            }
        }
        
        function addCategory(name) {
            const categories = categoryData[currentCategoryType];
            const maxId = Math.max(...categories.map(c => c.id), 0);
            
            const newCategory = {
                id: maxId + 1,
                name: name,
                icon: selectedIcon,
                subcategories: []
            };
            
            categories.push(newCategory);
            
            $('#categoryModal').modal('hide');
            renderCategoryList(currentCategoryType);
            showToast('分类添加成功');
        }
        
        function addSubcategory(name) {
            if (!currentParentCategory) return;
            
            const subcategories = currentParentCategory.subcategories;
            const maxId = Math.max(...subcategories.map(s => s.id), 0);
            
            const newSubcategory = {
                id: maxId + 1,
                name: name,
                icon: selectedIcon
            };
            
            subcategories.push(newSubcategory);
            
            $('#categoryModal').modal('hide');
            renderSubcategoryList(currentParentCategory);
            showToast('二级分类添加成功');
        }
        
        function updateCategory(categoryId, name) {
            const category = findCategoryById(categoryId, currentCategoryType);
            if (!category) return;
            
            category.name = name;
            category.icon = selectedIcon;
            
            $('#categoryModal').modal('hide');
            renderCategoryList(currentCategoryType);
            showToast('分类更新成功');
        }
        
        function updateSubcategory(categoryId, name) {
            const subcategory = findSubcategoryById(categoryId, currentParentCategory);
            if (!subcategory) return;
            
            subcategory.name = name;
            subcategory.icon = selectedIcon;
            
            $('#categoryModal').modal('hide');
            renderSubcategoryList(currentParentCategory);
            showToast('二级分类更新成功');
        }
        
        function deleteCategory(categoryId, isSubcategory) {
            const confirmMessage = isSubcategory ? '确定要删除这个二级分类吗？' : '确定要删除这个分类吗？\n删除后该分类下的所有二级分类也会被删除。';
            
            if (confirm(confirmMessage)) {
                if (isSubcategory) {
                    const index = currentParentCategory.subcategories.findIndex(s => s.id === categoryId);
                    if (index > -1) {
                        currentParentCategory.subcategories.splice(index, 1);
                        renderSubcategoryList(currentParentCategory);
                        showToast('二级分类删除成功');
                    }
                } else {
                    const index = categoryData[currentCategoryType].findIndex(c => c.id === categoryId);
                    if (index > -1) {
                        categoryData[currentCategoryType].splice(index, 1);
                        renderCategoryList(currentCategoryType);
                        showToast('分类删除成功');
                    }
                }
            }
        }
        
        // 图标选择事件
        $(document).on('click', '.icon-option', function() {
            $('.icon-option').removeClass('selected');
            $(this).addClass('selected');
            selectedIcon = $(this).data('icon');
        });
        
        // 模态框关闭事件
        $(document).on('hidden.bs.modal', '#categoryModal', function() {
            $(this).remove();
        });
        
        function showToast(message) {
            // 创建提示消息
            const toast = document.createElement('div');
            toast.className = 'toast-message';
            toast.textContent = message;
            document.body.appendChild(toast);
            
            // 3秒后自动移除
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 3000);
        }
    </script>
</body>
</html>